﻿using System;
using UnityEngine;
using EnCode=System.Text.Encoding;

public class MsgBase
{
    public string protoName = "";

    public static byte[] Encode(MsgBase msgBase)
    {
        string s = JsonUtility.ToJson(msgBase);
        return EnCode.Default.GetBytes(s);
    }

    public static MsgBase Decode(string protoName, byte[] bytes, int offset, int count)
    {
        string s = EnCode.UTF8.GetString(bytes, offset, count);
        MsgBase msgBase = (MsgBase)JsonUtility.FromJson(s, Type.GetType(protoName));
        return msgBase;
    }

    public static byte[] EncodeName(MsgBase msgBase)
    {
        byte[] nameBytes = EnCode.UTF8.GetBytes(msgBase.protoName);
        Int16 len = (Int16)nameBytes.Length;
        byte[] bytes = new byte[2 + len];
        bytes[0] = (byte)(len % 256);
        bytes[1] = (byte)(len / 256);
        
        Array.Copy(nameBytes,0,bytes,2,len);

        return bytes;
    }

    public static string DecodeName(byte[] bytes, int offset, out int count)
    {
        count = 0;

        if (offset+2>bytes.Length)
        {
            return "";
        }

        Int16 len = (Int16)((bytes[offset + 1] << 8) | bytes[offset]);

        if (offset+2+len>bytes.Length)
        {
            return "";
        }

        count = 2 + len;
        string name = EnCode.UTF8.GetString(bytes, offset + 2, len);

        return name;
    }
}

public class MsgMove : MsgBase
{
    public MsgMove()
    {
        protoName = "MsgMove";
    }

    public int x = 0;
    public int y = 0;
    public int z = 0;
}

public class MsgAttack : MsgBase
{
    public MsgAttack()
    {
        protoName = "MsgAttack";
    }

    public string desc = "127.0.0.1:6543";
}